package com.boot2.core.dao.jpa;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @ClassName: LogicalExpression
 * @description: 逻辑条件表达式 用于复杂条件时使用，如但属性多对应值的OR查询等
 * @author zhangweilin
 * @date 2017年12月27日 上午11:13:53
 *
 */
public class LogicalExpression implements Criterion {
	private Criterion[] criterionArr; // 逻辑表达式中包含的表达式
	private Operator operator; // 计算符

	public LogicalExpression(Criterion[] criterionArr, Operator operator) {
		this.criterionArr = criterionArr;
		this.operator = operator;
	}

	@Override
	public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
		List<Predicate> predicateList = new ArrayList<Predicate>();
		for (int i = 0; i < this.criterionArr.length; i++) {
			predicateList.add(this.criterionArr[i].toPredicate(root, query, builder));
		}
		switch (operator) {
		case OR:
			return builder.or(predicateList.toArray(new Predicate[predicateList.size()]));
		default:
			return null;
		}
	}

}